<template>
  <div class="wrapper">
    <div class="container">
      <div class="login_box">
        <div class="title">绑定手机号</div>
        <div class="login">
          <input clickVoice="true" class="phone" type="text" maxlength="11" v-model="formData.phone" @blur="inputBlur" placeholder="手机号">
          <div class="verfi_box">
            <input clickVoice="true" type="text" v-model="formData.verfi" @blur="inputBlur" placeholder="验证码">
            <span clickVoice="true" v-if="verfiStatus == true" @click="getVerfi">获取验证码</span>
            <span v-else>{{verfiTime}}</span>
          </div>
          <div clickVoice="true" class="btn_login btnHover" @click="verfiCode">绑定</div>
        </div>

      </div>

      <div class="logo">
        <img src="../assets/img/logo.png" alt="">
      </div>
    </div>
    <audio id='clickVoice' ref="clickVoice"  src="http://www.mingxiaoclub.cn/zebraOnline/voice/click.mp3" ></audio>
  </div>
</template>

<style scoped>
.wrapper {
  background: #FFD33D;
}

.login_box {
  padding: 0 .533333rem;
  padding-top: 2.373333rem;
  box-sizing: border-box;
}
.title {
  width: 4.133333rem;
  height: 1.333333rem;
  background: #fff;
  border-radius: .346667rem .346667rem 0 0;
  color: #FE8697;
  font-size: .586667rem;
  font-weight: 600;
  display: flex;
  justify-content: center;
  align-items: center;
}
.login {
  background: #fff;
  border-radius: 0 .48rem .48rem .48rem;
  min-height: 9.026667rem;
  text-align: center;
}

.logo {
  width: 3.333333rem;
  margin: 0 auto;
  margin-top: 1.92rem;
}
.logo img {
  width: 100%;
}

input {
  font-size: .48rem;
  padding: .453333rem .533333rem;
  box-sizing: border-box;
  background: #eee;
  border: none;
}
.phone {
  width: 80%;
  margin-top: 1.12rem;
  border-radius: .8rem;
}

.login .verfi_box {
  width: 80%;
  margin: 0 auto;
  text-align: left;
  display: flex;
  margin-top: .6rem;
}
.verfi_box input {
  width: 60%;
  border-radius: .8rem 0 0 .8rem;
}
.verfi_box span {
  display: inline-block;
  width: 40%;
  background: #FE8697;
  color: #fff;
  border-radius: 0 .8rem .8rem 0;
  font-size: .48rem;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn_login {
  width: 3.453333rem;
  height: 1.56rem;
  background: #FE8697;
  border-radius: .8rem;
  color: #fff;
  font-size: .506667rem;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
  margin-top: .88rem;
}
</style>

<script>
const wx = require('weixin-js-sdk');
import {
  createNamespacedHelpers
} from "vuex";
let {
  mapState,
  mapGetters,
  mapMutations,
  mapActions
} = createNamespacedHelpers("adminBasic");

export default {
  name: 'login',
  data() {
    return {
      formData: {
        phone: '',
        verfi: '',
        openId: '',
      },
      verfiStatus: true,
      verfiTime: 60,
    }
  },

  created() {
    
    // 微信相关
    this.initWxConfig();

    // 跳转获取微信 openId
    this.initWxOpenId();
  },

  mounted() {
    let audio = document.getElementById('clickVoice');
    
    document.ontouchstart = function(e) {
      console.log(e.target)
      // console.log(e.target.getAttribute("clickVoice"));
      if(e.target.getAttribute("clickVoice")) {
        audio.play();
      }
    }
  },

  methods: {
    ...mapActions([
      "formGet",
      "post"
    ]),
    ...mapMutations([
      "updateInfo"
    ]),

    

    verfiCode() {
      this.formGet({
        API: 'checkVerificationCode',
        data: {
          mobile: this.formData.phone,
          verificationCode: this.formData.verfi,
        }
      }).then(res => {
        console.log(res)
        this.bindPhone();
      }).catch(err => {
        this.$notify({ type: 'danger', message: err, duration: 1200 });
      })
    },

    queryStudentByOpenId() {
      this.formGet({
        API: 'queryStudentByOpenId',
        data: {
          openId: this.formData.openId
        }
      }).then(res => {
        console.log(res);
        if(res.openId) {    // 查询返回有学员信息， 直接跳转登录
          this.$router.replace({
            name: 'personCenter',
            params: {
              openId: res.openId,
            }
          })
        }
      }).catch(err => {

      })
    },

    bindPhone() {
      if(!this.formData.phone) {
        this.$notify({ type: 'danger', message: '请输入手机号', duration: 1200 });
        return false;
      }
      if(!this.formData.verfi) {
        this.$notify({ type: 'danger', message: '请输入验证码', duration: 1200 });
        return false;
      }

      this.formGet({
        API: 'bindMobilNumber',
        data: {
          mobile: this.formData.phone,
          openId: this.formData.openId,
        }
      }).then(res => {
        console.log(res);
        if(res) {   // 查询到该用户，直接跳转到用户中心
          this.$router.replace({
            name: 'personCenter',
            params: {
              openId: this.formData.openId
            },
          })
        }else{
          this.$router.replace({
            name: 'babyInfo',
            params: this.formData,
          })
        }
      })
    },
    getVerfi() {
      this.verfiStatus = false;
      let timer = setInterval(() => {
        this.verfiTime -= 1;
        if(this.verfiTime == 0) {
          clearInterval(timer)
          this.verfiStatus = true;
          this.verfiTime = 60
        }
      }, 1000)
      
      this.formGet({
        API: 'sendVerificationCode',
        data: {
          mobile: this.formData.phone,
        }
      }).then(res => {
        console.log(res)
        
      }).catch(err => {
        this.$notify({ type: 'danger', message: err, duration: 1200 });
				// this.$message.error(err);
      })

      
    },

    inputBlur() {
      window.scrollTo(0, document.documentElement.clientHeight); 
    },

    initWxConfig() {
      let _this = this;
      let url = window.location.href.split('#')[0];
      url = encodeURIComponent(url)
      console.log(url);
      this.$axios.get(`http://39.105.125.149:8060/banma/getTimestampNonceStrSignature?url=${url}`)
      .then(res => {
        res = res.data.data
        // console.log(res)
        wx.config({
          debug: false, // 开启调试模式,
          appId: 'wx6461e3736f9366e9', // 必填，企业号的唯一标识，此处填写企业号corpid
          timestamp: res.timestamp, // 必填，生成签名的时间戳
          nonceStr: res.nonceStr, // 必填，生成签名的随机串
          signature: res.signature,// 必填，签名，见附录1
          // jsApiList: ['openlocation', 'getLocation',] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
          jsApiList: ['chooseImage','uploadImage','getLocalImgData','downloadImage'],
        });

        wx.ready(function(){
          // 在这里调用 API
          wx.checkJsApi({
            jsApiList: [
              'chooseImage',
              'uploadImage',
              'getLocalImgData',
              'downloadImage'
            ],
            success: function (res) {
              console.log(JSON.stringify(res));
            }
          });
        })

        wx.error(function(err){
          console.log(err)
        })


      }).catch(err => {
        
      })
    },
    initWxOpenId() {
      let url = window.location.href;
      url = encodeURIComponent(url)
      // console.log(url)
      let code = this.getUrlParam('code')
      if(!code) {
        window.location.replace(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6461e3736f9366e9&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`)
      } else {
        this.wxCode = code;
        this.$axios.get(`http://39.105.125.149:8060/banma/getOpenId?code=${this.wxCode}`)
        .then(res => {
          console.log('微信openId：' + res.data.data)   // openId
          this.formData.openId = res.data.data;
          
          this.queryStudentByOpenId();
        }).catch(res => {
          
        })
      }
      console.log(this.wxCode);

      
    },
    getUrlParam(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    },
  }
}
</script>

